import React, { Component } from 'react'
import { connect } from 'dva';
import { Button, message, Card } from 'antd';

interface Props {
  dispatch?: Function,
  details: {
    name: string,
    typeName: string,
    itemList: any,
    defaultItem: Array<string>,
  },
  match: {
    params: {
      id: number
    }
  }
}

@connect(({ unit_template_question }) => ({
  details: unit_template_question.details
}))
class Details extends Component<Props, any> {

  state = {
    item_data: [],
    name: '',
    typeName: '',
    hasMsg: null,
    answer: null
  };

  componentWillMount() {
    this.state.hasMsg = message.loading('');
  }

  componentDidMount() {
    const { dispatch, match } = this.props;
    const { params } = match;
    dispatch({
      type: 'unit_template_question/queryInfoById',
      payload: params.id
    }).then(() => {
      const { details } = this.props;
      this.setState({
        name: details.name,
        typeName: details.typeName,
        item_data: details.itemList ? details.itemList : [],
        answer: details.itemList && details.defaultItem ? this.getAns(details.defaultItem, details.itemList) : null
      }, this.state.hasMsg)
    })
  }

  getAns(ans:Array<string>, qus: Array<any>) {
    const res = Array.isArray(ans) &&  Array.isArray(qus)? ans.map(it => qus.find(v => v.id === it)).map(w => w.context) : ''

    return res && Array.isArray(res) ? res.join('、') : ''
  }

  render() {
    return (
      <>
        <div style={{'marginBottom': '30px'}}>
          <Card
            title={this.state.name ? `${this.state.name} (${this.state.typeName})` : ''}
            style={{ width: '80%' }}
          >
            <>
            {
              this.state.item_data.map((item, index) => (
                <p key={index}>{index + 1}、{item.context}</p>
              ))
            }
            {
              this.state.answer && <p>正确答案: {this.state.answer}</p>
            }
            </>
          </Card>
        </div>
        <Button onClick={ () => {
          window.history.back();
        } }>返回</Button>
      </>
    );
  }
}

export default Details;


